package main

import (
	"fmt"
	"google.golang.org/grpc"
	stream "grpc/stream_grpc_test/proto"
	"net"
	"sync"
	"time"
)

const PORT = ":8088"

type server struct {
}

// GetStream 服务端流模式
func (s *server) GetStream(req *stream.StreamReqData, res stream.Greeter_GetStreamServer) error {
	i := 0
	for true {
		_ = res.Send(&stream.StreamResData{Data: fmt.Sprintf("%v - %d", time.Now().Format("2006-01-02 15:04:05"), i)})
		time.Sleep(time.Second)
		if i > 10 {
			break
		}
		i++
	}
	return nil
}

// PutStream 客户端流模式
func (s *server) PutStream(cliStr stream.Greeter_PutStreamServer) error {
	for {
		recv, err := cliStr.Recv()
		if err != nil {
			fmt.Println(err)
			break
		}

		fmt.Println(recv.GetData())
	}
	return nil
}

// AllStream 双向流模式
func (s *server) AllStream(allStr stream.Greeter_AllStreamServer) error {
	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		defer wg.Done()
		for {
			recv, _ := allStr.Recv()
			fmt.Println("收到客户端消息:", recv.Data)
		}
	}()

	go func() {
		defer wg.Done()
		for {
			_ = allStr.Send(&stream.StreamResData{Data: "我是服务端"})
			time.Sleep(time.Second)
		}
	}()

	wg.Wait()
	return nil
}

func main() {
	listen, err := net.Listen("tcp", PORT)
	if err != nil {
		panic(err)
	}

	newServer := grpc.NewServer()
	stream.RegisterGreeterServer(newServer, &server{})
	err = newServer.Serve(listen)
	if err != nil {
		panic(err)
	}
}
